import { InboxOutlined } from "@ant-design/icons";
import { Button, Dropdown, message, Space } from 'antd';
import Dragger from "antd/lib/upload/Dragger";
import React, { useEffect, useState } from 'react';

import Increase from './increase';
import axios from 'axios';
import { DOWNLOAD_TEMPLATE, COMPANY_UPLOAD_FILES } from '../../../constants/api-constants';
import xlsx from 'node-xlsx';
import FileSaver from 'file-saver';
import { useRequest } from 'ahooks';
import * as APIS from '../../../constants/api-constants';
/**
 * 详细信息设置
 * 批量导入和添加人才信息
 */

interface Props {
  setFresh: () => void;
}
export default ({ setFresh }: Props) => {
  const [showIncrease, setShowIncrease] = useState(false);
  const [medicalFieldList, setMedicalFieldList] = useState<CM.OptionItem[]>([]);
  const [businessList, setBusinessList] = useState<CM.OptionItem[]>([]);
  const [type, setTypeList] = useState<CM.OptionItem[]>([]);
  const { run: requestOptionList } = useRequest(() => {
    return {
      url: APIS.GET_COMPANY_OPTION_LIST,
      method: 'GET',
    };
  }, {
    manual: true,
    onSuccess: (result) => {
      const { medicalOptionList, businessOptionList, typeList } = result.data.mainData;
      console.log(medicalOptionList, businessOptionList, typeList);
      setBusinessList(businessOptionList);
      setMedicalFieldList(medicalOptionList);
      setTypeList(typeList);
    },
    onError: () => {
      message.error('服务器异常，请稍后再试');
      console.log('onError');
    },
  });
  useEffect(() => { requestOptionList() }, [requestOptionList])
  const templateHead = [
    '企业名称',
    '组织机构代码',
    '地址(用英文;分割)',
    '医疗领域',
    '企业类型',
    '主营业务',
    '成立时间',
    '企业简介'
  ];
  const propsw: any = {
    name: 'file',
    action: COMPANY_UPLOAD_FILES,
    headers: { Authorization: localStorage.getItem('Authorization') },
    data: { filler: localStorage.getItem('userName') },
    beforeUpload(file: File) {
      return new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = () => {
          if (reader.result && typeof reader.result !== 'string') {
            const buf = reader.result;
            const parse = xlsx.parse(buf, { type: 'buffer' });
            const { data } = parse[0];
            console.log(data);

            const errData = data.slice(0, 3);
            let dataFilter = data.filter((item: any[], index: number) => {
              let flag = true;
              // 忽略批量上传文件的前三行
              let errItem: any = [];
              if (index !== 0 && index !== 1 && index !== 2) {
                errItem = [];
                for (let i = 0; i < templateHead.length; i++) {
                  // 忽略检查
                  if (i === 1 || i === 6) {
                    continue;
                  } else if (!item[i]) {
                    // 检查每一列不为空
                    flag = false;
                    errItem.push(i);
                  }

                  // 检查医疗领域
                  if (i === 3 && !medicalFieldList.some(v => v.name === item[i])) {
                    flag = false;
                    errItem.push(i);
                  }
                  // 企业类型
                  if (i === 4 && !type.some(v => v.name === item[i])) {
                    flag = false;
                    errItem.push(i);
                  }
                  // 主营业务

                  if (i === 5) {
                    // eslint-disable-next-line no-loop-func
                    item[i].split(';').forEach((k: string) => {
                      if (!businessList.some(v => v.name === k)) {
                        flag = false;
                        errItem.push(i);
                      }
                    })
                  }
                  // 检查居住地
                  if (i === 2 && !/^.*?;.*?;.*?;.*?$/gi.test(item[i])) {
                    flag = false;
                    errItem.push(i);
                  }

                }
              }
              if (flag === false) {
                errData.push(
                  item.map((ceil, index) => {
                    if (errItem.some((v: any) => v === index)) {
                      return {
                        v: '(错误)' + ceil ?? '',
                        s: {
                          fill: {
                            fgColor: { rgb: 'FF0000' },
                          },
                        },
                      };
                    }
                    return ceil;
                  })
                );
              }
              return flag;
            });
            console.log('筛选数据', dataFilter);
            console.log('错误数据', errData);

            if (JSON.stringify(data[0]) !== JSON.stringify(templateHead)) {
              console.log(JSON.stringify(data[0]));
              console.log(JSON.stringify(templateHead));

              message.error(
                '上传文件中首行不正确请重试(请下载模板文件查看)',
                15
              );
            } else {
              const blob = new Blob(
                [xlsx.build([{ name: 'template', data: dataFilter }])],
                {
                  type: 'application/octet-stream',
                }
              );
              if (dataFilter.length !== data.length) {
                message.info('已将筛选出正确数据并上传', 15);
                message.info('已返回错误数据文件', 15);
                const blob1 = new Blob(
                  [xlsx.build([{ name: 'errData', data: errData }])],
                  {
                    type: 'application/octet-stream',
                  }
                );
                FileSaver.saveAs(blob1, 'errData.xlsx');
              }
              resolve(blob);
            }
          } else {
            message.error('文件读取失败请检查格式');
          }
        };
      });
    },
    onChange(info: {
      file: {
        response: { msg: string };
        status: string;
        name: string;
      };
      fileList: any;
    }) {
      if (info.file.status === 'done') {
        setFresh();
        message.success(`${info.file.name} 上传成功.`);
        message.success(info.file.response.msg);
      } else if (info.file.status === 'error') {
        setFresh();
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };
  const menu = (
    <div
      style={{
        background: 'rgb(251,251,251)',
        padding: '12px',
        boxShadow: '3px 3px 3px 3px rgb(193,193,195)',

        borderRadius: '3px',
      }}
    >
      <Button
        onClick={() => {
          axios
            .post(DOWNLOAD_TEMPLATE, {
              filename: "companyTemplate.xlsx",
              dir: "company",
            })
            .then((r) => {
              const { file, filename } = r.data.mainData;
              const cols: { width: number; type: string }[] = [];
              let blob = new Blob(
                [
                  xlsx.build(file, {
                    "!cols": cols,
                  }),
                ],
                {
                  type: "application/octet-stream",
                }
              );
              FileSaver.saveAs(blob, filename);
            })
            .catch(() => { });
        }}
        style={{
          overflow: 'hidden',
          whiteSpace: 'normal',
          wordBreak: 'break-all',
          fontSize: '0.9rem',
          padding: '0',
          width: '10vw',
          height: 'auto',
          marginBottom: '2vh',
        }}
      >
        下载导入模板
      </Button>
      <Dragger accept={'.xlsx'} {...propsw} style={{ padding: '0 1vw' }}>
        <p className='ant-upload-drag-icon'>
          <InboxOutlined />
        </p>
        <p className='ant-upload-text'>请拖拽.XLSX文件至此或使用点击上传</p>
        <p className='ant-upload-hint'>
          支持单次或批量上传。 严禁上传公司资料或其他公司文件
        </p>
      </Dragger>
    </div>
  );
  return (
    <>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <h2 style={{ fontWeight: 'bold', display: 'inline-block' }}>
          详细信息
        </h2>
        {
          window.localStorage.getItem('identity') === null ?
            null
            :
            <Space>
              <Dropdown
                trigger={['click']}
                placement='bottomRight'
                arrow
                overlay={menu}
              >
                <Button type='primary'>批量导入</Button>
              </Dropdown>
              <Button type='primary' onClick={() => { setShowIncrease(true) }}>
                添加企业信息
              </Button>
            </Space>
        }
      </div>
      <Increase
        showIncrease={showIncrease}
        setShowIncrease={setShowIncrease}
        setFresh={setFresh}
      />
    </>
  );
}
